package ar.com.fiuba.RulesMgr.validationModes;

import java.util.LinkedList;
import java.util.List;

import ar.com.fiuba.RulesMgr.rules.CompositeRule;
import ar.com.fiuba.RulesMgr.rules.GenericRule;

/**
 * Validation mode that considers the order of the applied rules.
 * 
 */
public class OrderedValidationMode implements ValidationMode {

	/**
	 * @link {@link ValidationMode#validate(GenericRule, List)}
	 */
	public Boolean validate(CompositeRule rule, List<Object> objects) {
		List<Object> auxList = new LinkedList<Object>(objects);
		Boolean leftRuleResult = Boolean.FALSE;
		Boolean rightRuleResult = Boolean.FALSE;
		int count = 0;
		int firstTruePosition = 0;

		while (count < auxList.size()) {
			leftRuleResult = rule.getLeftRule().validateWithMode(this, auxList.subList(0, count + 1));
			if (leftRuleResult && firstTruePosition == 0)
				firstTruePosition = count;
			count++;
		}

		if (!leftRuleResult || firstTruePosition == auxList.size() - 1)
			return Boolean.FALSE;

		auxList = auxList.subList(firstTruePosition + 1, auxList.size());
		count = 0;

		while (count < auxList.size()) {
			rightRuleResult = rule.getRightRule().validateWithMode(this, auxList.subList(0, count + 1));
			count++;
		}

		return rule.getConnector().evaluate(leftRuleResult, rightRuleResult);
	}
}
